#include"network.h"

void Errno()
{
    std::cout<<"argv is errno,because argc is not equal!"<<std::endl;
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Errno();
        exit(LOG_LEVEL_MAIN);
    }

    //创建套接字
    int cd = socket(AF_INET,SOCK_DGRAM,0);
    if(cd==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
        exit(LOG_LEVEL_SOCKET);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"socket is successful!");
    }

    //发送数据
    const char* ptr="Hello,你吃了吗！";
    struct sockaddr_in local;
    local.sin_family=AF_INET;
    local.sin_addr.s_addr=inet_addr(argv[1]);
    local.sin_port=htons(atoi(argv[2]));

    struct sockaddr_in local_s;
    socklen_t sz=sizeof(local);

    char buffer[1024]={'\0'};
 
    while(1)
    {
        ssize_t ac =sendto(cd,ptr,strlen(ptr),0,(const sockaddr*)&local,sizeof(local));
        if(ac==-1)
        {
            log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
            exit(LOG_LEVEL_SENDTO);
        }

        //接收信息
        ssize_t re= recvfrom(cd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&local_s,&sz);
        if(re==-1)//根据-1来判断是错误还是没有数据
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK) 
            {
            //没有数据，稍等片刻再试
            printf("暂时没有数据，等待...\\n");
            sleep(1);
            } 
            else 
            {
                //发生其他错误，处理错误
                log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码:%d,错误原因:%s",errno,strerror(errno));
                exit( LOG_LEVEL_RECVFROM);
            }
        }
        else
        {
            buffer[re] = 0;
            std::cout<<"我接收到你的回信了:"<<buffer<<std::endl;
            sleep(1);
        }
    }
    
    
    return 0;
}